package com.rgs.gateway.web.common.design.sign.strategy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.rgs.gateway.common.enums.SignTypeEnum;
import com.rgs.gateway.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * @author RenGaoshuai
 * @date 2024/7/1 16:45
 * @description
 */
@Slf4j
public class DataGatewaySignStrategy implements GatewaySignStrategy {

    @Override
    public String getSign(String appKey, String appSecret, String timestamp, Map<String, Object> params) {
        try {

            byte[] secretBytes = MessageDigest.getInstance("md5")
                    .digest((appSecret + JSON.toJSONString(params, SerializerFeature.MapSortField))
                            .getBytes(StandardCharsets.UTF_8));
            return new BigInteger(1, secretBytes).toString(16);
        } catch (NoSuchAlgorithmException e) {
            log.error("数据中台验签生成数据异常,异常信息为：{}",e.getMessage());
            throw new ServiceException("数据中台验签生成数据异常");
        }
    }

    @Override
    public Integer getSignType() {
        return SignTypeEnum.DATACENTER.getCodeValue();
    }
}
